<template>
    <div style="height: 100%" class="order-alert" v-hasPermi="['prewarn:read']">
        <el-container style="height: 100%">
            <el-main>
                <div class="content-wrapper">
                    <div class="flex search">
                        <div class="flex describe">
                            <div class="flex">
                                <div class="kxx-margin">
                                    门店数：
                                    {{ orderData.storeNum }}
                                </div>
                                <div class="kxx-margin">
                                    订单数：
                                    {{ orderData.orderNum }}
                                </div>
                                <div class="kxx-margin">
                                    客单价：
                                    {{ orderData.unitPrice }}
                                </div>
                                <div class="kxx-margin">
                                    交易额：
                                    {{ orderData.turnover }}
                                </div>
                                <div class="kxx-margin">
                                    取消率：
                                    {{ percent(orderData.cancelRate) }}
                                </div>
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="除一分钟取消订单的取消率"
                                    placement="top"
                                >
                                    <div class="kxx-margin">
                                        取消率(除急速退款)
                                        {{ percent(orderData.excludeOneMinCancelRate) }}
                                    </div>
                                </el-tooltip>

                                <div class="kxx-margin">
                                    缺陷率：
                                    {{ percent(orderData.defectRate) }}
                                </div>

                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    :content="orderData.temporaryData"
                                    placement="top"
                                >
                                    <div class="kxx-margin">
                                        30单以上门店占比：
                                        {{ percent(orderData.storeOrder30Rate) }}
                                    </div>
                                </el-tooltip>
                            </div>
                        </div>
                        <div class="flex">
                            <div v-if="userName">{{ userName }}</div>
                        </div>
                    </div>
                    <div class="flex">
                        <el-select
                            v-model="orderData.tradeID"
                            placeholder="营业状态"
                            size="large"
                            style="width: 140px; margin-right: 10px"
                            clearable
                        >
                            <el-option
                                v-for="item in orderData.tradeData"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                        <el-input
                            v-model.trim="orderData.storeId"
                            placeholder="门店ID/门店名称"
                            clearable
                            size="large"
                            style="width: 150px; margin-right: 10px"
                        />
                        <div style="width: 230px">
                            <el-date-picker
                                prefix-icon="prefix-icon-class"
                                size="large"
                                v-model="queryTerm.time"
                                @change="datapicker"
                                type="daterange"
                                unlink-panels
                                range-separator="~"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                style="width: 200px"
                            />
                        </div>

                        <el-button :loading="loading" type="primary" plain class="kxx-btn-primary" @click="Refresh"
                            >刷新</el-button
                        >
                        <el-button class="kxx-btn-primary" @click="openWarnSetting" v-hasPermi="['prewarn:setting']"
                            >预警率设置</el-button
                        >
                        <el-button
                            class="kxx-btn-primary"
                            style="width: 120px"
                            @click="accountManagement"
                            v-if="!userName"
                            v-hasPermi="['prewarn:subUserList']"
                            >子账号数据预警</el-button
                        >
                        <el-button
                            class="kxx-btn-primary"
                            style="width: 120px"
                            @click="openOrderAlert"
                            v-hasPermi="['prewarn:tenMinutesList']"
                            >到期订单预警</el-button
                        >
                        <el-button-group class="ml-4">
                            <el-button
                                class="kxx-btn-primary"
                                style="width: 120px"
                                @click="ScanOrderExport(0)"
                                v-hasPermi="['prewarn:orderExport']"
                                >订单详情导出</el-button
                            >
                            <el-button class="kxx-btn-primary" @click="ScanOrderExport(1)" :icon="Download"
                                >导出</el-button
                            ><el-button class="kxx-btn-primary" v-hasPermi="['prewarn:config']" @click="markCancelAll()"
                                >取消标记</el-button
                            >
                            <el-popover
                                trigger="click"
                                ref="setRemovePop"
                                placement="bottom"
                                style="padding: 0"
                                :width="230"
                            >
                                <div class="kxx-checkbox">
                                    <div class="kxx-checkAll">
                                        <el-checkbox
                                            v-model="checkAll"
                                            :indeterminate="isIndeterminate"
                                            @change="handleCheckAllChange"
                                            >全选</el-checkbox
                                        >
                                        <el-button size="large" type="primary" link @click="restore"
                                            >恢复默认</el-button
                                        >
                                    </div>

                                    <el-checkbox-group v-model="selectedColumns">
                                        <el-checkbox
                                            v-for="column in allColumnsRef"
                                            :key="column.key"
                                            :label="column.key"
                                            :disabled="column.fixed"
                                            :draggable="!column.fixed"
                                            @dragstart="handleDragStart(column, $event)"
                                            @dragover="handleDragOver($event)"
                                            @drop="handleDrop(column, $event)"
                                        >
                                            {{ changeName(column.label) }}
                                            <!-- <span v-html="column.label"></span> -->
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </div>
                                <template #reference>
                                    <el-button
                                        class="kxx-btn-primary"
                                        size="default"
                                        :icon="Setting"
                                        style="width: 40px"
                                    ></el-button>
                                </template>
                            </el-popover>
                        </el-button-group>
                    </div>
                    <div class="table-wrapper">
                        <el-table
                            :data="
                                tableData.slice(
                                    (orderData.page - 1) * orderData.limit,
                                    orderData.page * orderData.limit,
                                )
                            "
                            :header-cell-style="{ 'text-align': 'left' }"
                            :default-sort="{ prop: 'orderNum', order: 'descending' }"
                            @sort-change="handleSortChange"
                            border
                            :cell-style="cellStyle"
                            highlight-current-row
                            v-loading="tableLoading"
                            :row-class-name="rowClassName"
                            :ref="tableRef"
                        >
                            <el-table-column
                                v-for="item in visibleTableColumns"
                                :key="item.key"
                                :prop="item.key"
                                :label="item.label"
                                :show-overflow-tooltip="true"
                                :sortable="item.sortable"
                                :width="visibleTableColumns.length < 15 ? 'auto' : item.width"
                                :fixed="item.fixed"
                                :cell-style="cellStyle"
                                :resizable="true"
                                :min-width="item.minwidth"
                                :formatter="
                                    (row, column, cellValue, index) => {
                                        return cellValue || item.default
                                    }
                                "
                            >
                                <template #header>
                                    <span v-html="item.label"></span>
                                </template>
                                <template #default="scope" v-if="item.label == '服务等级'">
                                    <div class="flex">
                                        <div class="status-point" :class="styleColor(scope.row?.serviceLevel)"></div>
                                        {{ scope.row?.serviceLevelDescr }}
                                    </div>
                                </template>
                                <template #default="scope" v-else-if="item.label == '营业状态'">
                                    <div>
                                        {{ tradeName(scope.row?.openLevel) }}
                                    </div>
                                </template>
                                <template #default="scope" v-else-if="item.label == '取消率'">
                                    <div :class="setWarningColor('Cancellation', scope.row?.cancelRate)">
                                        {{ percent(scope.row?.cancelRate, '-') }}
                                    </div>
                                </template>
                                <template #default="scope" v-else-if="item.label == '预估取消率'">
                                    <div v-if="warningDataRef && warningDataRef.Cancellation.length">
                                        {{ getEstimatedCancellation(scope.row) }}
                                    </div>
                                    <div v-else>--</div>
                                </template>

                                <template #default="scope" v-else-if="item.label == '取消率(除<br/>急速退款)'">
                                    <div :class="setWarningColor('', scope.row?.excludeOneMinCancelRate)">
                                        {{ percent(scope.row?.excludeOneMinCancelRate, '-') }}
                                    </div>
                                </template>

                                <template #default="scope" v-else-if="item.label == '配送超时率'">
                                    <div :class="setWarningColor('Timeout', scope.row?.deliveryTimeoutRate)">
                                        {{ percent(scope.row?.deliveryTimeoutRate, '-') }}
                                    </div>
                                </template>
                                <template #default="scope" v-else-if="item.label == '缺陷率'">
                                    <div :class="setWarningColor('Defect', scope.row?.defectRate)">
                                        {{ percent(scope.row?.defectRate, '-') }}
                                    </div>
                                </template>
                                <template #default="scope" v-else-if="item.label == '预估缺陷率'">
                                    <div v-if="warningDataRef && warningDataRef.Defect.length">
                                        {{ getEstimatedDefectRate(scope.row) }}
                                    </div>
                                    <div v-else>--</div>
                                </template>
                                <template #default="scope" v-else-if="item.label == '标记'">
                                    <el-button
                                        class="btn-mark"
                                        :class="scope.row?.mark ? 'kxx-front-red' : ''"
                                        :icon="scope.row?.mark ? StarFilled : Star"
                                        link
                                        @click="markChange(scope.row)"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- 底部分页 -->
                        <div class="pagination_css flex">
                            <div class="flex">
                                <div class="kxx-margin flex" v-for="item in orderData.summary" :key="item.level">
                                    <div :class="styleColor(item.level)" class="status-point"></div>
                                    {{ item.label }}： {{ item.count }}
                                </div>
                            </div>

                            <el-pagination
                                v-model:currentPage="orderData.page"
                                v-model:page-size="orderData.limit"
                                :page-sizes="orderData.pageSizeOptions"
                                background
                                layout="total, sizes, prev, pager, next"
                                :total="orderData.total"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                            />
                        </div>
                    </div>
                </div>
            </el-main>
        </el-container>
        <AccountManage ref="accountManage" @placeAnOrderBtn="changeOrder" />
        <orderEarlyWarning v-model:visible="dialogTableVisible"></orderEarlyWarning>
        <WarningSetting v-model:visible="warnSetting" @submit="Refresh()"></WarningSetting>
    </div>
</template>
<script setup>
import { ElLoading } from 'element-plus'
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { alertApi } from '@/api/orderAlert'
import { exportToExcel } from '@/utils/excelUtils'
import { Download, Setting, StarFilled, Star } from '@element-plus/icons-vue'
import { CancelToken } from 'axios'
// import { MarkClass, columns, cities, disabledColumns } from './data'
import { useStore } from 'vuex'
import { MarkClass, tableColumns as defaultColumns } from './data'
import AccountManage from './components/accountManage.vue' //子账号弹框
import WarningSetting from './components/warningSetting.vue' // 预警率设置
import orderEarlyWarning from './components/orderEarlyWarning.vue' // 预警率设置
import { exportFile } from '@/utils/downloadFile' //导出表格

import storage from '@/utils/storage'

/** 登录账号 */
let loginAccount = localStorage.getItem('ms_username')
const accountManage = ref()
const store = useStore()
/**子账号iD */
const userID = ref('')
/**子账号名称 */
const userName = ref('')
const checkAll = ref(false)
const isIndeterminate = ref(false)
const loading = ref(false)
const tableLoading = ref(false)
const tableRef = ref(null)
const queryTerm = reactive({
    /**日期 */
    time: '',
    /**开始时间 */
    // eslint-disable-next-line camelcase
    start_time: '',
    /**结束时间 */
    // eslint-disable-next-line camelcase
    end_time: '',
})
const data = ref([])
const dialogTableVisible = ref(false)
const orderData = reactive({
    page: 1, // 当前页码
    limit: 50, // 每页显示条数  limit
    tableData: [], //列表数据
    total: 0, //总数
    pageSizeOptions: [10, 50, 100, 150, 200], // 指定每页可以显示多少条
    /**自动刷新开关 */
    switchVal: false,
    timer: null,
    /**品牌门店数 */
    storeNum: 0,
    /**门店服务等级 */
    summary: {},
    /**品牌订单数 */
    orderNum: 0,
    /**品牌客单价 */
    unitPrice: 0,
    /**品牌取消率 */
    cancelRate: '',
    /**品牌缺陷率 */
    defectRate: '',
    storeId: '',
    /**要排序的名称 */
    prop: '',
    /**初始排序的顺序 */
    order: '',
    excludeOneMinCancelRate: 0, //除一分钟取消订单的取消率
    turnover: 0,
    tradeData: [
        {
            id: 0,
            name: '休息',
        },
        {
            id: 1,
            name: '营业',
        },
    ],
    tradeID: '',
    UserData: null,
    /**间隔时长数据 */
    interval: [
        {
            key: 5000,
            name: '5秒',
        },
        {
            key: 10000,
            name: '10秒',
        },
        {
            key: 60000,
            name: '1分钟',
        },
    ],
    /**间隔时长 */
    intervalTime: 5000,
    /**30单以上门店占比 */
    storeOrder30Rate: '',
    temporaryData: '',
})

const allColumnsRef = ref([])

const checkPermission = async () => {
    const result = await store.dispatch('checkPermissionsFn', 'prewarn:config')
    return result
}

let tagData = {}

const warningDataRef = ref([]) //缓存值

onMounted(async () => {
    let hasPermission = await checkPermission()
    if (!hasPermission) {
        defaultColumns.forEach(item => {
            if (item.key === 'mark') {
                item.visible = false
            }
        })
    }
    allColumnsRef.value = JSON.parse(JSON.stringify(defaultColumns))
    loading.value = true
    tableLoading.value = true
    UserInfo()
    parseURLParams()
    if (userID.value) {
        changeOrder()
    } else {
        querydataAnalysis(0)
    }
    // 获取预警率设置 的缓存值
    warningDataRef.value = storage.get('warningData')
})

//订单预警（10分钟）弹窗
const openOrderAlert = () => {
    dialogTableVisible.value = true
}

function UserInfo() {
    // 分页条数
    let alertLimit = localStorage.getItem('alert_limit')

    initTableHeader()

    setCheckbox(selectedColumns.value)

    tagData = JSON.parse(localStorage.getItem(MarkClass + loginAccount)) || {}
    if (alertLimit) orderData.limit = Number(alertLimit)
}

async function initTableHeader() {
    let cacheTableColumns = getTableColumnsFromLocalStorage()
    if (!Array.isArray(cacheTableColumns) || cacheTableColumns.length == 0) return

    let allColumns = allColumnsRef.value
    let tableColumns = []
    cacheTableColumns.forEach(item => {
        // if (!item.visible) return

        let column = allColumns.find(p => p.key == item.key)
        if (column) {
            // add column
            column.visible = item.visible
            tableColumns.push(column)
        }
    })

    allColumns.forEach((item, index) => {
        if (
            (item.fixed && tableColumns.findIndex(p => p.key == item.key) < 0) ||
            (item.visible && cacheTableColumns.findIndex(p => p.key == item.key) < 0) // 如果没有在本地存储中找到列，则可能是新增的列
        ) {
            // 新增的列和固定的列如果不存在，则加入
            tableColumns.splice(index, 0, item)
        }
    })

    // console.log(allColumnsRef.value, 'allColumnsRef.value')
    allColumnsRef.value = tableColumns
}

/** 定义解析 URL 参数的函数 */
const parseURLParams = () => {
    // console.log(new URLSearchParams(window.location.search), 'URLSearchParams(window.location.search)')
    const params = new URLSearchParams(window.location.search)
    // console.log(params, '定义解析 URL 参数的函数')
    userID.value = params.get('userId') || ''
    userName.value = params.get('userName') || ''
    // eslint-disable-next-line camelcase
    queryTerm.start_time = params.get('startTime') || ''
    // eslint-disable-next-line camelcase
    queryTerm.end_time = params.get('endTime') || ''
    if (queryTerm.start_time && queryTerm.end_time) {
        queryTerm.time = [queryTerm.start_time, queryTerm.end_time]
    } else {
        datapicker()
    }
}
const visibleTableColumns = computed(() => {
    return allColumnsRef.value.filter(column => column.visible)
})

/**时间选择器触发事件 */
const datapicker = temp => {
    if (!temp) {
        temp = [new Date(), new Date()]
    }

    queryTerm.time = temp
    // eslint-disable-next-line camelcase
    queryTerm.start_time = new Date(temp[0])
        .toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
        .replace(/\//g, '-')

    let endTime = new Date(temp[1])
    endTime.setDate(endTime.getDate() + 1) // 将结束时间增加一天
    // eslint-disable-next-line camelcase
    queryTerm.end_time = new Date(endTime)
        .toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
        .replace(/\//g, '-')
    if (userID.value) {
        changeOrder()
    } else {
        querydataAnalysis(1)
    }
}
// 导出订单
const ScanOrderExport = type => {
    let exportName = type ? '美团门店数据分析' : '订单详情'
    if (!type) {
        let obj = {
            startDate: queryTerm.start_time,
            endDate: queryTerm.end_time,
        }
        let fm = new FormData()
        fm.append('startDate', obj.startDate)
        fm.append('endDate', obj.endDate)
        alertApi.detailsExport(fm).then(res => {
            exportFile(res)
        })
    } else {
        // 创建Loading实例并立即显示
        const loadingInstance = ElLoading.service({
            fullscreen: true, // 你可以根据需要设置全屏或其他选项
            text: '导出中...',
        })
        setTimeout(() => {
            exportToExcel(type, orderData.tableData, exportName, loadingInstance)
        }, 50)
    }
}
// 一页几条
const handleSizeChange = ev => {
    orderData.limit = ev
    localStorage.setItem('alert_limit', orderData.limit)
}
// 下一页、上一页
const handleCurrentChange = ev => {
    orderData.page = ev
}
const cancelTokenArr = reactive({
    list: [],
})
/**
 * 订单数据
 *
 * @param {type} type  0浏览器刷新、1用户操作页面内刷新
 *  */
const querydataAnalysis = type => {
    loading.value = true
    tableLoading.value = true
    let obj = { startDate: queryTerm.start_time, endDate: queryTerm.end_time }
    setTimeout(() => {
        cancelTokenArr.list.forEach(item => {
            item('取消了')
        })

        alertApi
            .dataAnalysis(obj, {
                cancelToken: new CancelToken(c => cancelTokenArr.list.push(c)),
            })
            .then(res => {
                if (res.data.code == 0) {
                    let responseData = res.data.data
                    data.value = responseData.list
                    // console.log('直接获取后台', data.value)
                    orderData.tableData = responseData.list

                    setMark(responseData.list)

                    orderData.total = responseData.list.length

                    orderData.storeNum = responseData.overview.shopNum
                    orderData.summary = responseData.overview.levelSummary
                    orderData.orderNum = responseData.overview.orderNum
                    orderData.unitPrice = responseData.overview.avgPrice
                    orderData.cancelRate = responseData.overview.cancelRate
                    orderData.defectRate = responseData.overview.defectRate
                    orderData.excludeOneMinCancelRate = responseData.overview.excludeOneMinCancelRate
                    let temporaryData = responseData.list.filter(item => {
                        if (Number(item.monthFinishedNum) > 30) return item
                    })
                    orderData.temporaryData = `30单以上门店 ${temporaryData.length} 家`
                    if (responseData.list.length) {
                        orderData.storeOrder30Rate = temporaryData.length / responseData.list.length
                    }
                    // 交易额（交易额 = 客单价 * 订单数）
                    orderData.turnover = (orderData.unitPrice * orderData.orderNum).toFixed(2)
                    nextTick(() => {
                        if (type == 0) {
                            let defaultSort = {
                                prop: 'orderNum', // 初始排序的属性名
                                order: 'descending', // 初始排序的顺序 降序
                            }
                            handleSortChange(defaultSort)
                        } else {
                            let defaultSort = {
                                prop: orderData.prop, // 初始排序的属性名
                                order: orderData.order, // 初始排序的顺序 降序
                            }
                            handleSortChange(defaultSort)
                        }
                    })
                    loading.value = false
                    tableLoading.value = false
                } else {
                    loading.value = false
                    tableLoading.value = false
                }
            })
        // .finally(() => {
        //     loading.value = false
        //     tableLoading.value = false
        // })
    }, 100)
}

function setMark() {
    // if (Object.keys(tagData).length === 0) {
    //   delete data.mark;
    // }
    let dataList = orderData.tableData
    for (let i = 0, item; (item = dataList[i]); i++) {
        item.mark = tagData[item.wmPoiId]
    }
}

const percent = function (dec, defaultStr) {
    if (!dec && defaultStr) return defaultStr

    if (dec <= 1) {
        return (dec * 100).toFixed(2) + '%'
    }
    return dec //'Please enter number less than or equal to 1'
}
const selectedColumns = computed({
    // getter
    get() {
        return allColumnsRef.value.filter(p => p.visible).map(p => p.key)
    },
    // setter
    set(selectedColumns) {
        setCheckbox(selectedColumns)

        allColumnsRef.value.forEach(item => {
            item.visible = selectedColumns.findIndex(key => item.key == key) >= 0
        })

        updateTableColumnsToLocalStorage()
    },
})

function setCheckbox(selectedColumns) {
    let checkedCount = selectedColumns.length
    let totalCount = allColumnsRef.value.length
    checkAll.value = checkedCount === totalCount
    isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount
}

const tableData = computed(() => {
    let keyword = orderData.storeId.trim()
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    data.value ??= []
    // console.log('计算前', data.value)
    const filteredData = data.value.filter(item => {
        let isOpenCondition = orderData.tradeID === '' ? true : item.openLevel == orderData.tradeID
        let storeIdCondition =
            keyword === '' ? true : item.wmPoiId.toString().startsWith(keyword) || item.poiName.startsWith(keyword)

        return isOpenCondition && storeIdCondition
    })
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    orderData.total = filteredData.length
    orderData.total

    // console.log('计算后的', filteredData)
    return filteredData
})

/**排序 */
function handleSortChange(sort) {
    const { prop, order } = sort
    orderData.prop = prop
    orderData.order = order

    data.value.sort(function (a, b) {
        const valueA = isNaN(parseFloat(a[prop])) ? 0 : parseFloat(a[prop])
        const valueB = isNaN(parseFloat(b[prop])) ? 0 : parseFloat(b[prop])
        if (order === 'ascending') {
            return valueA - valueB
        } else {
            return valueB - valueA
        }
    })

    orderData.tableData = data.value
}

/**全选 */
function handleCheckAllChange(checked) {
    if (checked) {
        selectedColumns.value = allColumnsRef.value.map(column => column.key)
    } else {
        selectedColumns.value = allColumnsRef.value.filter(column => column.fixed).map(column => column.key)
    }
}

// const BA_SHOP_ANALYSIS_TABLE_VIEW = 'BA_shop_analysis_table_view'
const BA_SHOP_ANALYSIS_TABLE_COLUMN = 'BA_shop_analysis_table_column'
function updateTableColumnsToLocalStorage() {
    let arr = allColumnsRef.value.map(item => {
        return {
            key: item.key,
            visible: item.visible,
        }
    })

    localStorage.setItem(BA_SHOP_ANALYSIS_TABLE_COLUMN, JSON.stringify(arr))
}

function getTableColumnsFromLocalStorage() {
    try {
        let arrColumns = JSON.parse(localStorage.getItem(BA_SHOP_ANALYSIS_TABLE_COLUMN))
        return arrColumns
    } catch {
        return []
    }
}

/**动态添加样式 */
function cellStyle({ row }) {
    // 标记
    if (row.mark) return { color: '#fd1e1e' }
}
/**恢复默认 */
function restore() {
    allColumnsRef.value = JSON.parse(JSON.stringify(defaultColumns))

    updateTableColumnsToLocalStorage()
}
/** 去掉 <br/>*/
function changeName(val) {
    switch (val) {
        case '申请退款<br/>商家原因':
            return '申请退款-商家原因'
        case '申请退款<br/>用户原因':
            return '申请退款-用户原因'
        case '配送超时<br/>订单数':
            return '配送超时订单数'
        case '1分钟取<br/>消订单':
            return '1分钟取消订单'
        default:
            return val
    }
}
/** 头部-服务等级-添加color */
function styleColor(val) {
    switch (val) {
        case 4:
            return 'kxx-green'
        case 3:
            return 'kxx-blue'
        case 2:
            return 'kxx-orange'
        case 1:
            return 'kxx-red'
        case 0:
            return 'kxx-grey'
        default:
            return val
    }
}
/**营业状态 */
function tradeName(val) {
    return val == 3 ? '休息中' : val == 1 ? '营业' : ''
}
/**拖拽 */
const handleDragStart = (column, event) => {
    event.dataTransfer.setData('text/plain', column.key)
}
/**拖拽时持续触发 */
const handleDragOver = event => {
    event.preventDefault()
}
/**拖拽元素放置到目标元素上 */
const handleDrop = (val, event) => {
    const draggedColumn = event.dataTransfer.getData('text/plain')
    let fromIndex = null
    let toIndex = null
    let add = null

    allColumnsRef.value.forEach((item, index) => {
        if (item.fixed) return // 固定列不能拖拽更改位置

        if (item.key == draggedColumn) {
            fromIndex = index
        }
        if (val.key == item.key) {
            toIndex = index
        }
        if (item.key == draggedColumn) {
            add = item
        }
    })

    if (toIndex && fromIndex && fromIndex > -1 && toIndex > -1) {
        allColumnsRef.value.splice(fromIndex, 1)
        allColumnsRef.value.splice(toIndex, 0, add)

        updateTableColumnsToLocalStorage()
    }
}

/**打开账号管理页面 */
function accountManagement() {
    accountManage.value.openaccountManage(queryTerm.start_time, queryTerm.end_time)
}

const warnSetting = ref(false)
/**打开预警值设置 */
function openWarnSetting() {
    warnSetting.value = true
}
/** 获取子账号数据*/
function changeOrder() {
    loading.value = true
    tableLoading.value = true
    let obj = {
        startDate: queryTerm.start_time,
        endDate: queryTerm.end_time,
        userId: userID.value,
    }
    alertApi
        .getSubuserShopAnalysis(obj)
        .then(res => {
            if (res.data.code == 0) {
                let responseData = res.data.data
                if (responseData.list) {
                    data.value = responseData.list
                    orderData.tableData = responseData.list
                    orderData.total = responseData.list.length
                }
                orderData.storeNum = responseData.overview.shopNum
                orderData.summary = responseData.overview.levelSummary
                orderData.orderNum = responseData.overview.orderNum
                orderData.unitPrice = responseData.overview.avgPrice
                orderData.cancelRate = responseData.overview.cancelRate
                orderData.defectRate = responseData.overview.defectRate
                let temporaryData = responseData.list.filter(item => {
                    if (Number(item.monthFinishedNum) > 30) return item
                })
                orderData.temporaryData = `30单以上门店 ${temporaryData.length} 家`
                if (responseData.list.length) {
                    orderData.storeOrder30Rate = temporaryData.length / responseData.list.length
                }
                // 交易额（交易额 = 客单价 * 订单数）
                orderData.turnover = (orderData.unitPrice * orderData.orderNum).toFixed(2)
                loading.value = false
                tableLoading.value = false
                nextTick(() => {
                    let defaultSort = {
                        prop: orderData.prop, // 初始排序的属性名
                        order: orderData.order, // 初始排序的顺序 降序
                    }
                    handleSortChange(defaultSort)
                })
            }
        })
        .finally(() => {
            loading.value = false
            tableLoading.value = false
        })
}
//刷新
function Refresh() {
    if (userID.value) {
        changeOrder()
    } else {
        querydataAnalysis(1)
    }

    warningDataRef.value = storage.get('warningData')
}

// 获取 预估取消率
function getEstimatedCancellation(row) {
    // 取消率是通过 取消单数除以推单数 获取；
    // 预估取消率是 通过当前这行的 取消单率cancellation 与 Cancellation数组中每一项比较 value值，value值可能会带有小数点7.6
    // 如果 tableData 中 商家3的 预估取消率  是 6%，需要返回 推单数增加多少单 退单率就降低到5%，展示效果： 预估取消率 5%--(增加？单)；
    // 如果 tableData 中 商家3的 预估取消率  是 5%，需要返回 展示效果： 预估取消率 5%--(增加0单)；

    const warningData = storage.get('warningData')
    if (warningData && warningData.Cancellation.length) {
        const currentCancellationRate = row.cancelRate * 100 //当前取消率
        let additionalOrders = 0
        let nearestValue = storage.get('warningData')?.CancellationRadioValue //选中的对比的取消率值

        if (nearestValue && nearestValue < currentCancellationRate) {
            nearestValue = parseFloat(nearestValue)

            // 如果当前取消率和最近的阈值相等，返回预估取消率为0
            if (currentCancellationRate === nearestValue) {
                return `${nearestValue}% (差0单)`
            }

            // 计算需要增加多少单，取消率会降低到最近的阈值
            const cancelNumber = parseFloat(row.cancelOrderNum) //取消单
            const totalNumber = parseFloat(row.pushOrderNum) //推广单

            additionalOrders = Math.ceil(cancelNumber / (nearestValue / 100) - totalNumber)

            return `${nearestValue}% (差${additionalOrders}单)`
        }

        return `--`
    }
}
// 获取预估缺陷率
function getEstimatedDefectRate(row) {
    const warningData = storage.get('warningData')
    if (warningData && warningData.Defect.length) {
        const currentDefectRate = row.defectRate * 100 //缺陷率

        let additionalOrders = 0

        let nearestValue = storage.get('warningData')?.DefectRadioValue //选中的对比的缺陷率值

        if (nearestValue && nearestValue < currentDefectRate) {
            nearestValue = parseFloat(nearestValue)

            // 如果当前缺陷率和最近的阈值相等，返回预估缺陷率为0
            if (currentDefectRate === nearestValue) {
                return `${nearestValue}% (差0单)`
            }

            // 计算需要增加多少单，缺陷率会降低到最近的阈值
            const cancelNumber = parseFloat(row.defectOrderNum) // 缺陷单
            const totalNumber = parseFloat(row.pushOrderNum) //推广单

            additionalOrders = Math.ceil(cancelNumber / (nearestValue / 100) - totalNumber)

            return `${nearestValue}% (差${additionalOrders}单)`
        }

        return `--`
    }
}

// 设置预警值颜色
function setWarningColor(type, num) {
    if (!num) return
    let data = localStorage.getItem('warningData') ? JSON.parse(localStorage.getItem('warningData')) : []
    if (!data || !data[type]) return
    data[type] = data[type].sort((a, b) => {
        return a.value - b.value
    })
    let flag
    for (let index = 0; index < data[type].length; index++) {
        const element = data[type][index]
        if (Number(num) >= Number(element.value / 100)) {
            flag = index
        }
    }

    return flag == undefined ? '' : data[type][flag].colorValue
}
// 标记
function markChange(row) {
    const namespacedKey = MarkClass + loginAccount
    if (tagData[row.wmPoiId]) tagData[row.wmPoiId] = 0
    else tagData[row.wmPoiId] = 1 //row.mark;

    row.mark = tagData[row.wmPoiId]

    localStorage.setItem(namespacedKey, JSON.stringify(tagData))
    // markref.value[row.index].hide();
    // setMark();
}
/**标记全部取消 */
function markCancelAll() {
    if (!confirm('确定取消所有标记吗？')) return
    // markref.value[row.index].hide();
    const namespacedKey = MarkClass + loginAccount
    tagData = {}
    localStorage.setItem(namespacedKey, JSON.stringify(tagData))

    setMark()
}
function rowClassName({ row, rowIndex }) {
    //把每一行的索引放进row
    row.index = rowIndex
}
</script>
<style lang="less" scoped>
.btn-mark {
    // width: 100%;
    // justify-content: start;
    min-width: 40px;
}
.status-point {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 100%;
    margin-right: 8px;
}
.kxx-green {
    background-color: #00d450;
}
.kxx-blue {
    background-color: #349fc1;
}
.kxx-orange {
    background-color: #ff8800;
}
.kxx-red {
    background-color: #fd1e1e;
}

.kxx-front-red {
    color: #fd1e1e !important;
}

.kxx-grey {
    background-color: #aaaaaa;
}
.header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
}

.content-wrapper {
    display: flex;
    flex-direction: column;
    height: 100%;
    /* padding: 20px; */
    /* background-color: #fff; */
}
.table-wrapper {
    height: 0;
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    margin-top: 20px;
}
.search {
    margin-bottom: 20px;
    justify-content: space-between;
}

.pagination_css {
    justify-content: space-between;
    padding-top: 20px 0;
}
:deep(.cell) {
    white-space: nowrap;
}
.kxx-margin {
    margin: 0 10px;
}
.describe {
    flex-direction: row;
    flex-wrap: wrap;
}
:deep(.el-checkbox) {
    width: 100%;
    margin-right: 0px;
}
.el-checkbox-group {
    height: 400px;
    overflow: hidden;
    overflow: auto;
    padding: 12px;
}

.kxx-checkAll {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    padding-top: 5px;
}
.kxx-checkAll .el-button {
    margin-right: 5px;
    font-size: 14px;
}
.kxx-checkAll .el-checkbox {
    width: 100px;
}

.user-name img {
    margin-top: 3px;
    width: 15px;
    height: 17px;
}
.user-name span {
    margin-left: 3px;
    font-size: 18px;
}
.brand h2 {
    margin-right: 15px;
}
.brand-name {
    color: #349fc1;
    margin-left: 5px;
}
.kxx-button {
    margin-right: 10px;
}

.red {
    color: #fb4c4c;
}
.orange {
    color: #ff8800;
}
.blue {
    color: #349fc1;
}
.el-radio-group {
    padding-left: 30px;
    border-bottom: 1px solid #e7e7e7;
}
.kxx-radio {
    /* text-align: center; */
    display: flex;
}
.el-button-group {
    display: flex;
}

.order-alert {
    :deep(.el-table th) {
        color: #333333 !important;
        background-color: #fbfbfb !important;
        height: 56px;
        font-size: 16px;
        font-weight: 400;
    }
}
.kxx-btn-primary {
    height: 38px !important;
    margin-left: 10px;
    width: 90px;
}
</style>
